package com.mall.order.mq;

import com.alibaba.fastjson.JSON;
import com.mall.order.OrderPromoService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dto.CreateSeckillOrderRequest;
import com.mall.order.dto.CreateSeckillOrderResponse;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
public class PromoOrderConsumer {

    private DefaultMQPushConsumer consumer;

    @Autowired
    OrderPromoService orderPromoService;

    @PostConstruct
    public void init() {
        consumer = new DefaultMQPushConsumer("promo_order_consumer");

        consumer.setNamesrvAddr("127.0.0.1:9876");

        consumer.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {


                MessageExt message = msgs.get(0);
                byte[] body = message.getBody();
                String jsonStr = new String(body, 0, body.length, StandardCharsets.UTF_8);

                CreateSeckillOrderRequest request = JSON.parseObject(jsonStr, CreateSeckillOrderRequest.class);

                CreateSeckillOrderResponse promoOrderResponse = orderPromoService.createPromoOrder(request);


                //  下游事务没有失败这个说法【即使程序永远不会返回正确结果，也会加入死信队列等待运行】
                //          1. 如果正确就返回success
                //          2. 如果没成功就重试，重试到一定次数，就加入死信队列。
                if (OrderRetCode.SUCCESS.getCode().equals(promoOrderResponse.getCode())) {
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                } else {
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }


            }
        });

        try {
            consumer.subscribe("promo_order", "*");

            consumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }

    }


}
